﻿#include "rpc_router.h"

#include "log.h"

const char LOG_NAME[] = "CRpcRouter";

CRpcRouter::CRpcRouter()
{
}

CRpcRouter::~CRpcRouter()
{
}

uint16_t CRpcRouter::GetDstSvrId(uint64_t uRpcCltId,
	const std::string& sService, const std::string& sMethod) const
{
	// 先在自己路由表中查找
	const Router* pCltRtr = GetCltRouter(uRpcCltId);
	if (pCltRtr)
	{
		uint16_t uSvrId = GetDstSvrId(*pCltRtr, sService, sMethod);
		if (uSvrId) return uSvrId;
	}

	// 再在全局路由表中查找
	return GetDstSvrId(m_globalRouter, sService, sMethod);
}

uint16_t CRpcRouter::GetIdBySvcMthd(const Svc2Mthds& svc2Mthds,
	const string& sService, const string& sMethod) const
{
	auto itr = svc2Mthds.find(sService);
	if (itr == svc2Mthds.end()) return 0;
	const Mthd2SvrId& mthd2Id = (*itr).second;
	return GetIdFromMap(mthd2Id, sMethod);
}

uint16_t CRpcRouter::GetIdBySvc(const Svc2SvrId& svc2SvrId,
	const string& sService) const
{
	return GetIdFromMap(svc2SvrId, sService);
}

uint16_t CRpcRouter::GetIdFromMap(const Str2Id& str2Id, const string& s) const
{
	auto itr = str2Id.find(s);
	if (itr == str2Id.end()) return 0;
	return (*itr).second;
}

void CRpcRouter::SetMthdDstSvrId(const string& sService, const string& sMethod,
	uint16_t uSvrId)
{
	LOG_DEBUG(Fmt("Set method route: global %s.%s -> %u") % sService % sMethod % uSvrId);
	m_globalRouter.svc2Mthds[sService][sMethod] = uSvrId;
}

void CRpcRouter::SetMthdDstSvrId(uint64_t uRpcCltId, const string& sService,
	const string& sMethod, uint16_t uSvrId)
{
	LOG_DEBUG(Fmt("Set method route: Clt%u %s.%s -> %u")
		% uRpcCltId % sService % sMethod % uSvrId);
	m_rpcCltId2Router[uRpcCltId].svc2Mthds[sService][sMethod] = uSvrId;
}

void CRpcRouter::SetSvcDstSvrId(const string& sService, uint16_t uSvrId)
{
	LOG_DEBUG(Fmt("Set service route: global %s -> %u") % sService % uSvrId);
	m_globalRouter.svc2SvrId[sService] = uSvrId;
}

void CRpcRouter::SetSvcDstSvrId(uint64_t uRpcCltId,
	const string& sService, uint16_t uSvrId)
{
	LOG_DEBUG(Fmt("Set service route: Clt%u %s -> %u")
		% uRpcCltId % sService % uSvrId);
	m_rpcCltId2Router[uRpcCltId].svc2SvrId[sService] = uSvrId;
}

const CRpcRouter::Router* CRpcRouter::GetCltRouter(uint64_t uRpcCltId) const
{
	auto itr = m_rpcCltId2Router.find(uRpcCltId);
	if (itr == m_rpcCltId2Router.end()) return nullptr;
	return &(*itr).second;
}

uint16_t CRpcRouter::GetDstSvrId(const Router& router,
	const string& sService, const string& sMethod) const
{
	// 先按（服务，方法）查找，如果没有则按服务查找
	uint16_t uSvrId = GetIdBySvcMthd(router.svc2Mthds, sService, sMethod);
	if (uSvrId) return uSvrId;
	return GetIdBySvc(router.svc2SvrId, sService);
}

